package com.le.tester.imooc.masterJUC.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 描述：获取锁的过程中打断
 */
public class LockInterruptAble implements Runnable {

    private Lock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        LockInterruptAble lockInterruptAble = new LockInterruptAble();
        Thread thread0 = new Thread(lockInterruptAble);
        Thread thread1 = new Thread(lockInterruptAble);
        thread0.start();
        thread1.start();
        Thread.sleep(2000);

        thread1.interrupt();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " 尝试获取锁");

        //一个可中断的锁
        try {
            lock.lockInterruptibly();
            try {
                System.out.println(Thread.currentThread().getName() + " 获取到了锁");
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println("睡眠期间被中断,异常信息：" + e);
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " 释放了锁");
            }
        } catch (InterruptedException e) {
            System.out.println("等锁的期间被中断，异常信息：" + e);
        }
    }
}
